package Controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import Components.RequestUtil;
import Components.SessionUtil;
import Components.DAO.WBMessageCenterDao;
import Components.DB.Buser;
import Components.Service.UserMessageCenterService;

/**
 * Controller used for saving
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/save")
public class SaveController {

	private final String failPage = "public/SaveFail",
			successPage = "public/SaveSuccess";

	@Autowired
	WBMessageCenterDao wbMessageCenterDao;

	@Autowired
	UserMessageCenterService userMessageCenterService;

	/**
	 * <b><font color=red>save Web Blog</font></b> insert incoming data to
	 * Bwebblog table in database.
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/WBSave.do")
	public String WBSave(HttpServletRequest request, HttpSession session) {

		int Buser_Id = (Integer) session.getAttribute("Buser_Id");
		String Content = RequestUtil.getParamFromReq(request, "Content");
		int Type = Integer.parseInt(RequestUtil
				.getParamFromReq(request, "Type"));
		int Pre_Wb_Id = Integer.parseInt(RequestUtil.getParamFromReq(request,
				"Pre_Wb_Id"));

		boolean isSuccess = this.wbMessageCenterDao.writeWebBlog(Buser_Id,
				Content, Type, Pre_Wb_Id, null);
		if (isSuccess) {
			return successPage;
		} else {
			return failPage;
		}
	}

	@RequestMapping("/UserRegisterSave.do")
	public String UserRegisterSave(HttpServletRequest request,
			HttpSession session) {

		String username = RequestUtil.getParamFromReq(request, "username");
		String password = RequestUtil.getParamFromReq(request, "password");
		String remoteHost = request.getRemoteHost();

		/*
		 * register when there is not an existing user
		 */
		boolean isSuccess = this.userMessageCenterService.UserRegisterSave(
				username, password, remoteHost);
		if (isSuccess)
			return successPage;
		else
			return failPage;
	}

	@RequestMapping("/UserLogin.do")
	public String UserLogin(HttpServletRequest request) {
		String username = RequestUtil.getParamFromReq(request, "username");
		String password = RequestUtil.getParamFromReq(request, "password");

		Buser buser = null;
		try {
			buser = this.userMessageCenterService.queryUserFromName(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (buser != null && password.equals(buser.getPassword())) {
			SessionUtil.generateNewUID(request);
			return successPage;
		} else {
			return failPage;
		}
	}

}
